package com.app.mvc;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.NameValuePair;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhangzhiling on 2017/1/6.
 */
@Controller
public class Httpclient {

    private static final CloseableHttpClient httpClient;
    public static final String CHARSET = "UTF-8";
    static {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }

    @RequestMapping("/httpGet")
    @ResponseBody
    public void getSample () throws ClientProtocolException, IOException{

        String url = "https://www.baidu.com";

        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);

        HttpResponse response = client.execute(request);
        System.out.println("Response Code: " +
                response.getStatusLine().getStatusCode());

        BufferedReader rd = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));
        String line = "";
        while((line = rd.readLine()) != null) {
            System.out.println(line);
        }
    }

    @RequestMapping("/httpPost")
    public void postSample () throws ClientProtocolException, IOException{

        String url = "https://www.baidu.com";
        //将要访问的url字符串放入HttpPost中
        HttpPost httpPost = new HttpPost(url); // HttpGet httpGet = new HttpGet(url);
        //请求头 放置一些修改http请求头和cookie
        httpPost.setHeader("Accept", "application/json");
        //如果是HttpPost或者HttpPut请求需要在请求里加参数，而HttpGet或者HttpDelete请求则可以直接拼接到url字符串后面
        //向HttpPost中加入参数
        List<NameValuePair> values = new ArrayList<NameValuePair>();
        values.add(new BasicNameValuePair("id", "1"));
        values.add(new BasicNameValuePair("name", "xiaohong"));
        httpPost.setEntity(new UrlEncodedFormEntity(values, "UTF-8"));  //进行转码

      //实例HttpClient 并执行带有HttpPost的方法,返回HttpResponse 响应，再进行操作
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        int statusCode = httpResponse.getStatusLine().getStatusCode();  //返回状态码 ，用来进行识别或者判断访问结果
        if (statusCode != 200) {
            httpPost.abort();
            System.out.println("出错");
            throw new RuntimeException("HttpClient,error status code :" + statusCode);
        }
        HttpEntity entity = httpResponse.getEntity();
        String result = null;
        if (entity != null) {
            result = EntityUtils.toString(entity, "utf-8");
        }
        EntityUtils.consume(entity);
        httpResponse.close();
        System.out.println(result);

    }

}
